package yana.tpe.servlets.task1;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.IOUtils;

public class Controller extends HttpServlet {
    
    public static final String ROOT_FOLDER = System.getProperty("user.home");
    public static final String FILE_PARAMETER = "file";

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        String fileParameter = request.getParameter(FILE_PARAMETER);
        if (fileParameter == null || fileParameter.isEmpty()) {
            response.sendError(400, "Parameter " + FILE_PARAMETER + " not found.");
            return;
            
        }
        System.out.println("File name: " + fileParameter);
        
        File file = getFile(fileParameter);
        response.setContentType("text/html;charset=UTF-8");
        if (file == null || !file.exists() ){
            writeResponse(response, "<h1>ERROR:</h1>File " + file + " does not exist!");
        } else {
            StringBuilder sb = new StringBuilder();
            sb.append("<h1>File was found</h1>");
            sb.append("<p>File path: ").append(file).append("</p>");
            sb.append("<p>File size: ").append(file.length()).append("</p>");
            if (file.isFile() && checkFileExtension(file, "txt", "ini", "html")) {
                sb.append("<table border='1'><tr><td><pre>");
                FileInputStream fileInputStream = new FileInputStream(file);
                sb.append(IOUtils.toString(fileInputStream));
                IOUtils.closeQuietly(fileInputStream);
                sb.append("</pre></td></tr></table>");
            }
            writeResponse(response, sb.toString());
        }
    }
    
    protected File getFile(String fileName) {
        return new File(ROOT_FOLDER, fileName);
    }

    private void writeResponse(HttpServletResponse response, String body) throws IOException {
        PrintWriter out = response.getWriter();
        try {
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet Controller</title>");            
            out.println("</head>");
            out.println("<body>");
            out.println(body);
            out.println("</body>");
            out.println("</html>");
        } finally {            
            out.close();
        }
    }

    private boolean checkFileExtension(File file, String... extensions) {
        for (String string : extensions) {
            if (file.getName().endsWith(string)) {
                return true;
            }
        }
        return false;
    }
}
